<template>
    <div>
        <el-card>
            <el-button type="primary" :icon="Plus" @click="onAdd">添加品牌</el-button>
            <el-table :data="tableData" border style="margin: 10px 0;">
                <el-table-column label="序号" width="80" align="center" type="index"  />
                <el-table-column prop="tmName" label="品牌名称" align="center" />
                <el-table-column label="品牌LOGO" align="center">
                    <template #="{row,$index}">
                        <el-image :src="row.logoUrl" style="width: 100px; height: 100px" fit="cover" :preview-src-list="row.logoUrl.split(',')" :preview-teleported="true">
                            <template #error>
                            <div class="image-slot">
                                <el-icon><icon-picture style="width: 100%;height: 100%;"/></el-icon>
                            </div>
                            </template>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column label="品牌操作" align="center">
                    <template #="{row,$index}">
                        <el-button type="primary" size="small" :icon="Edit" @click="$event=>onEdit(row)"></el-button>
                        <el-popconfirm :title="`您确定要删除${row.tmName}?`" width="250" icon="Delete" icon-color="#ff0000" @confirm="onDel(row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" :icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination
            v-model:current-page="pageNo"
            v-model:page-size="limit"
            :page-sizes="[3, 5, 7, 9]"
            :background="true"
            layout="prev, pager, next, jumper,->,sizes,total "
            :total="total"
            @size-change="handleSizeChange"
            @current-change="getPageList"
            />
        </el-card>
        <!-- 对话框组件 -->
        <el-dialog v-model="dialogFormVisible" :title="type !='add'?'修改品牌':'添加品牌'">
            <el-form :model="form" style="width: 80%;" :rules="rules" ref="formRef">
                <el-form-item label="品牌名称" :label-width="100" prop="tmName">
                    <el-input placeholder="请输入品牌名称" v-model="form.tmName" />
                </el-form-item>
                <el-form-item label="品牌LOGO" :label-width="100" prop="logoUrl">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/admin/product/fileUpload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="onConfirm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang='ts'>
import { ref, onMounted,reactive,nextTick } from 'vue'
import { Plus,Picture as IconPicture,Edit,Delete } from '@element-plus/icons-vue'
import type {Records,TrademarkResponseData,Trademark} from '@/api/product/trademark/type'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
//引入接口
//@ts-ignore
import { requestPageList,save,update,get,del } from '@/api/product/trademark'

//分页属性
let pageNo = ref<number>(1) //页码从第一页开始
let limit = ref<number>(3) //每一页显示3条
let total = ref<number>(0)
let tableData = ref<Records>([])
let type = ref<string>()
let formRef = ref()

//列表接口
const getPageList = async( pager=1 )=>{
    pageNo.value = pager;
    let result:TrademarkResponseData = await requestPageList(pageNo.value,limit.value)
    if(result.code == 200){
        const { records } = result.data
        total.value = result.data.total
        tableData.value = records
    }
}

onMounted(()=>{
    getPageList();
})

const handleSizeChange = ()=>{
    getPageList();
}

//对话框属性
let dialogFormVisible = ref(false)
let form = reactive<Trademark>({
    tmName:'',
    logoUrl:''
})

//添加
const onAdd = ()=>{
    type.value = 'add'
    form.tmName = ''
    form.logoUrl = ''
    dialogFormVisible.value = true
    nextTick(()=>{
        formRef.value.clearValidate('tmName')
        formRef.value.clearValidate('logoUrl')
    })
}
//修改
const onEdit = async(row:Trademark)=>{
    formRef.value?.clearValidate()
    type.value = 'edit'
    try {
        let result = await get(row.id)
        if(result.code == 200){
            form.id = result.data.id
            form.tmName = result.data.tmName
            form.logoUrl = result.data.logoUrl
            dialogFormVisible.value = true
        }
    } catch (error) {}
}

//删除
const onDel = async (id:number)=>{
    try {
       let result = await del(id)
       if(result.code == 200){
        getPageList( tableData.value.length > 1 ? pageNo.value : pageNo.value - 1 );
        ElMessage.success('删除品牌成功')
       }else{
        ElMessage.error('删除品牌失败')
       }
    } catch (error) {
        
    }
}

//确定
const onConfirm = async ()=>{
    await formRef.value.validate()
    try {
        const result = type.value == 'add' ? await save(form) : await update(form)
        if(result.code == 200){
            getPageList();
            ElMessage.success(type.value == 'add'?'添加品牌成功':'修改品牌成功')
            dialogFormVisible.value = false
        }else{
            ElMessage.error(type.value == 'add'?'添加品牌失败':'修改品牌失败') 
        }
    } catch (error) {}
}

//图片上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
    if(rawFile.size / 1024 / 1024 < 4){
        return true
    }else{
        ElMessage.error('上传文件大小小于4M')
        return false
    }
  } else {
    ElMessage.error('上传文件格式务必是JPG|PNG|GIF')
    return false
  }
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
    form.logoUrl = response.data
    formRef.value.clearValidate('logoUrl')
}

//校验规则
const validatorTmName = (rule:any,value:any,callBack:any)=>{
    if(value.trim().length >= 2){
        callBack()
    }else{
        callBack(new Error('品牌名称位数大于等于两位'))
    }
}
const validatorLogoUrl = (rule:any,value:any,callBack:any)=>{
    if(value){
        callBack()
    }else{
        callBack(new Error('logo的图片务必上传'))
    }
}
const rules = {
    tmName:[
        {required: true,trigger: 'blur',validator: validatorTmName}
    ],
    logoUrl:[
        {required: true,trigger: 'change',validator: validatorLogoUrl}
    ]
}


</script>


<style scoped lang='scss'>
.el-icon{
    width: 100%;
    height: 100%;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>